package websocket

import (
	"encoding/json"
	"log"
	"sync"
)

// ChatMessage 聊天消息结构
type ChatMessage struct {
	MessageId   uint64 `json:"messageId"`
	MatchId     uint64 `json:"matchId"`
	SenderId    string `json:"senderId"`
	Content     string `json:"content"`
	MessageType int32  `json:"messageType"`
	CreateTime  string `json:"createTime"`
}

// MatchSuccessData 匹配成功推送结构体
type MatchSuccessData struct {
	MatchId    uint64  `json:"matchId"`
	UserId     string  `json:"userId"`
	NickName   string  `json:"nickName"`
	Avatar     string  `json:"avatar"`
	MatchScore float64 `json:"matchScore"`
	Reason     string  `json:"reason"`
}

// GlobalHub 全局WebSocket Hub管理器
type GlobalHub struct {
	hub *Hub
	mu  sync.RWMutex
}

var globalHub *GlobalHub
var once sync.Once

// GetGlobalHub 获取全局Hub实例（单例模式）
func GetGlobalHub() *GlobalHub {
	once.Do(func() {
		globalHub = &GlobalHub{
			hub: NewHub(),
		}
		go globalHub.hub.Run()
	})
	return globalHub
}

// GetHub 获取Hub实例
func (gh *GlobalHub) GetHub() *Hub {
	gh.mu.RLock()
	defer gh.mu.RUnlock()
	return gh.hub
}

// SendToUser 发送消息给特定用户
func (gh *GlobalHub) SendToUser(userId string, message []byte) {
	gh.mu.RLock()
	defer gh.mu.RUnlock()
	gh.hub.SendToUser(userId, message)
}

// SendChatNotification 发送聊天通知
func (gh *GlobalHub) SendChatNotification(receiverId string, message ChatMessage) {
	gh.mu.RLock()
	defer gh.mu.RUnlock()
	SendChatNotification(gh.hub, receiverId, message)
}

// SendMatchNotification 发送匹配通知
func (gh *GlobalHub) SendMatchNotification(userId string, matchId uint64, message string) {
	gh.mu.RLock()
	defer gh.mu.RUnlock()
	SendMatchNotification(gh.hub, userId, matchId, message)
}

// SendMatchSuccess 发送匹配成功推送
func (gh *GlobalHub) SendMatchSuccess(userId string, data *MatchSuccessData) {
	gh.mu.RLock()
	defer gh.mu.RUnlock()
	msg := Message{
		Type: "MATCH_SUCCESS",
		Data: data,
	}
	b, err := json.Marshal(msg)
	if err != nil {
		log.Printf("序列化匹配成功消息失败: %v", err)
		return
	}
	gh.hub.SendToUser(userId, b)
}

// GetConnectedUsers 获取已连接用户列表
func (gh *GlobalHub) GetConnectedUsers() []string {
	gh.mu.RLock()
	defer gh.mu.RUnlock()

	gh.hub.mu.RLock()
	userIds := make([]string, 0, len(gh.hub.userClients))
	for userId := range gh.hub.userClients {
		userIds = append(userIds, userId)
	}
	gh.hub.mu.RUnlock()

	return userIds
}

// SendChatNotification 发送聊天通知（内部函数）
func SendChatNotification(hub *Hub, receiverId string, message ChatMessage) {
	notification := Message{
		Type: "CHAT_MESSAGE",
		Data: message,
	}

	data, err := json.Marshal(notification)
	if err != nil {
		log.Printf("序列化聊天消息失败: %v", err)
		return
	}

	hub.SendToUser(receiverId, data)
}

// SendMatchNotification 发送匹配通知（内部函数）
func SendMatchNotification(hub *Hub, userId string, matchId uint64, message string) {
	notification := Message{
		Type: "MATCH_SUCCESS",
		Data: map[string]interface{}{
			"matchId": matchId,
			"message": message,
		},
	}

	data, err := json.Marshal(notification)
	if err != nil {
		log.Printf("序列化匹配通知消息失败: %v", err)
		return
	}

	hub.SendToUser(userId, data)
}

// WsManager 全局WebSocket管理器（单例）
var WsManager = GetGlobalHub()

